package com.aqie.easy.string;

/**
 * 541 反转字符串 2
 */
public class ReverseStr {
    /**
     * 1, 2ms
     * @param s
     * @param k
     * @return
     */
    public String reverseStr(String s, int k) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        for (int i = 0; i < len; i += k * 2){
            if (i + k <= len) overturn(chars, i, i + k);
            else              overturn(chars, i, len);
        }
        // chars 转 string
        String ans = new String(chars);
        return ans;
    }

    private void overturn(char[] chars, int fast, int last) {
        int i = fast;
        int j = last - 1;
        while (i < j){
            chars[i] ^= chars[j];
            chars[j] ^= chars[i];
            chars[i++] ^= chars[j--];
        }
    }


    /**
     * 2. 4ms
     * @param s
     * @param k
     * @return
     */
    public String reverseStr2(String s, int k) {
        StringBuilder sb = new StringBuilder();
        int len = s.length();
        int cur = 0;
        while(len >= 2*k){
            sb.append(new StringBuilder(s.substring(cur, cur+k)).reverse().append(s.substring(cur+k, cur+2*k)));
            len -= 2*k;
            cur += 2*k;
        }
        if(len < k){
            sb.append(new StringBuilder(s.substring(cur)).reverse());
        }else if(len < 2*k){
            sb.append(new StringBuilder(s.substring(cur, cur+k)).reverse().append(s.substring(cur+k)));
        }
        return sb.toString();
    }


}
